import React from 'react';
import {inject, observer} from 'mobx-react';
import {toJS} from 'mobx';

import {
  WeaTop,
  WeaLeftRightLayout,
  WeaLeftTree,
  WeaTools,
  WeaOrgTree,
  WeaTab,
  WeaFormItem,
  WeaSearchGroup,
  WeaRightMenu,
  WeaAlertPage,
  WeaDialog
} from 'ecCom';
import {Button} from 'antd';
import {WeaTableNew, WeaSwitch} from 'comsMobx';
const {WeaTable} = WeaTableNew;

import {WeaLocaleProvider} from 'ecCom';
const getLabel = WeaLocaleProvider.getLabel;

import MeetingDialog from '../public/dialog/index';
import RoomPlanDialog from '../public/roomPlan/index';

@inject('meetingMonitor')
@observer
export default class Monitor extends React.Component {
  constructor (props) {
    super(props);
    this.state = {
      RoomPlanContainer: false,
      meetingId: '',
      dialogType: 'preview',
      visible: false,
    }
  }

  componentDidMount() {
    const {meetingMonitor} = this.props;
    meetingMonitor.doInit();
  }

  componentWillReceiveProps(nextProps) {
    if (this.props.location.key !== nextProps.location.key) {
      this.doRefesh();
    }
  }

  componentWillUnmount() {
    const { meetingMonitor } = this.props;
    meetingMonitor.status.showSearchAd = false;
  }

  getSearchs(){
    const {meetingMonitor} = this.props;
    const {monitorForm, status} = meetingMonitor;
    const {conditioninfo} = status;
    const {isFormInit} = monitorForm;
    let group = [];
    const formParams = monitorForm.getFormParams();
    isFormInit && conditioninfo && conditioninfo.map((c, index) =>{
      let items = [];
      c.items.map(fields => {
        items.push({
          com:(<WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@129ltc@${fields.domkey[0]}`}
            label={`${fields.label}`}
            labelCol={{span: `${fields.labelcol}`}}
            wrapperCol={{span: `${fields.fieldcol}`}}>
            <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@1ivk75@${fields.domkey[0]}`} fieldConfig={fields} form={monitorForm} onEnterSearch={this.onEnterSearch}/>
          </WeaFormItem>),
          colSpan:1
        })
      });
      group.push(<WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@shiml0@${index}`} needTigger={true} title={c.title} showGroup={c.defaultshow} items={items}/>)
    });
    return group;
  }

  onEnterSearch = ()=>{
    const {meetingMonitor} = this.props;
    const formParams = monitorForm.getFormParams();
    meetingMonitor.setState({timeSag: formParams.timeSag})
    meetingMonitor.getMonitor(true);
    meetingMonitor.setState({showSearchAd: false})
  }

  getTabButtonsAd() {
    const {meetingMonitor} = this.props;
    const formParams = meetingMonitor.monitorForm.getFormParams();
    let btns=[
      <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@1rqzy0@doSearch`} type='primary' onClick={() => {
        meetingMonitor.setState({timeSag: formParams.timeSag})
        meetingMonitor.getMonitor(true);
        meetingMonitor.setState({showSearchAd: false})
      }}>{getLabel(197,'搜索')}</Button>,
      <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@h7hj2h@doReset`} type="ghost" onClick={() => meetingMonitor.monitorForm.reset()}>{getLabel(27088,'重置')}</Button>,
      <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@h1rwzh@doCancel`} type="ghost" onClick={() => meetingMonitor.setState({showSearchAd: false})}>{getLabel(31129,'取消')}</Button>,
    ]
    return btns;
  }

  getRightMenu() {
    const { monitorTableStore } = this.props.meetingMonitor;
    const rowSelectIds = toJS(monitorTableStore.selectedRowKeys);

    let btnArr = [
      {
        key: 'BTN_QUERY',
        icon: <i className='icon-coms-search'/>,
        content : `${getLabel(197,'搜索')}`,
        onClick : () => this.onRightMenuClick('BTN_QUERY')
      },
      {
        key: 'BTN_DEL',
        icon: <i className='icon-coms-delete'/>,
        content : `${getLabel(32136,'批量删除')}`,
        disabled :!rowSelectIds || rowSelectIds.length == 0,
        onClick : () => this.onRightMenuClick('BTN_DEL')
      },
      {
        key: 'BTN_EXPORTALL',
        icon: <i className='icon-coms-download'/>,
        content : `${getLabel(81272,'导出全部')}`,
        onClick : () => this.onRightMenuClick('BTN_EXPORT')
      },
      {
        key: 'BTN_COLUMN',
        icon: <i className='icon-coms-Custom'/>,
        content : `${getLabel(32535,'显示列定制')}`,
        onClick : () => this.onRightMenuClick('BTN_COLUMN')
      }
    ];
    return btnArr;
  }


  onOperatesClick = (record, index, operate, flag) => {
    const {meetingMonitor} = this.props;
    if(operate.index == '0'){//提前结束
      meetingMonitor.doConfirm(`${getLabel(126004,'确定要提前结束会议吗？')}`, meetingMonitor.monitorOver, {meetingid: record.id})
    }
    if(operate.index == '1'){//取消会议
      meetingMonitor.doConfirm(`${getLabel(20117,'你确定要取消会议吗？')}`, meetingMonitor.monitorCancel, {meetingid: record.id})
    }
    if(operate.index == '2'){//删除
      meetingMonitor.doConfirm(`${getLabel(82017,'确认删除？')}`, meetingMonitor.monitorDelete, {meetingids: record.id})
    }
  }

  onRightMenuClick = (type) => {
    const {meetingMonitor} = this.props;
    const {monitorTableStore} = meetingMonitor;
    const rowSelectIds = toJS(monitorTableStore.selectedRowKeys);
    if(type == "BTN_DEL"){
      if(rowSelectIds && rowSelectIds.length !== 0){
        meetingMonitor.doConfirm(`${getLabel(82017,'确认删除？')}`, meetingMonitor.monitorDelete, {meetingids: rowSelectIds.join(',')});
      }else {
        meetingMonitor.setModal(`${getLabel(24264, '请先选择会议')}`)
      }
    }else if(type == 'BTN_COLUMN'){
      monitorTableStore.setColSetVisible(true);
      monitorTableStore.tableColSet(true);
    }else if(type == 'BTN_QUERY'){
      meetingMonitor.getMonitor(true)
    }else if(type == 'BTN_EXPORT'){
      meetingMonitor.exportAll()
    }
  }

  getColumns = (columns) => {
    let newColumns = '';
    newColumns = columns.map(column => {
      let newColumn = column;
      newColumn.render = (text, record, index) => { //前端元素转义
        let valueSpan = record[newColumn.dataIndex + "span"] !== undefined ? record[newColumn.dataIndex + "span"] : record[newColumn.dataIndex];
        return (
          newColumn.dataIndex == 'name' ?
            <a onClick={() => {
              this.setState({meetingId: record.id, visible: true})
              this.setType('preview')
            }} dangerouslySetInnerHTML={{ __html: valueSpan }} />
            :
            <div className="wea-url" dangerouslySetInnerHTML={{ __html: valueSpan }} />
        )
      }
      return newColumn;
    });
    return newColumns;
  }

  //查看会议弹框引入
  setAll = (meetingId, bool, type)=>{
    this.setState({
      meetingId:meetingId,
      visible:bool,
      dialogType:type
    })
  }
  setMeetingId = (meetingId) => {
    this.setState({ meetingId: meetingId })
  }
  setRoomPlan = (bool) => {
    this.setState({ RoomPlanContainer: bool })
  }
  setDialog = (bool) => {
    this.setState({ visible: bool })
  }
  setType = (type) => {
    this.setState({ dialogType: type })
  }

  doRefesh = () => {
    const {meetingMonitor} = this.props;
    meetingMonitor.getMonitor();
  }

  render() {
    const { meetingMonitor } = this.props;
    const { monitorTableStore,status, monitorForm } = meetingMonitor;
    const { isAlertPage, timeSag, showSearchAd, previewVisible, previewId, delLoading} = toJS(status);
    const rowSelectIds = toJS(monitorTableStore.selectedRowKeys);
    const topTab = [
      {
        groupid: 'all',
        title: `${getLabel(332,'全部')}`,
        viewcondition: '0'
      },
      {
        groupid: 'today',
        title: `${getLabel(15537,'今天')}`,
        viewcondition: '1'
      },
      {
        groupid: 'theWeek',
        title: `${getLabel(15539,'本周')}`,
        viewcondition: '2'
      },
      {
        groupid: 'theMon',
        title: `${getLabel(130018,'本月')}`,
        viewcondition: '3'
      },
      {
        groupid: 'local',
        title: `${getLabel(21904,'本季')}`,
        viewcondition: '4'
      },
      {
        groupid: 'theYear',
        title: `${getLabel(126760,'本年')}`,
        viewcondition: '5'
      },
    ]
    const title = getLabel(17625,'会议监控');

    const collectParams={
      favname:title,
      favouritetype: 5,
      objid:0,
      //link:'wui/engine.html#/meetingengine/monitor',
      importantlevel: 1,
    };

    return (
      <div className="wea-meetingback-monitor">
        {!isAlertPage ?
          <div>
            <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@wcsjzn`}
              datas={this.getRightMenu()}
              collectParams={collectParams}>
              <WeaTop ecId={`${this && this.props && this.props.ecId || ''}_WeaTop@oo7k5q`}
                title={getLabel(17625,'会议监控')}
                icon={<i className='icon-coms-meeting' />}
                iconBgcolor='#F14A2D'
                showDropIcon={true}
                dropMenuDatas={this.getRightMenu()}
                dropMenuProps={{
                  collectParams:collectParams
                }}
                buttons={[
                  <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@picwzk@batchDelete`}
                    type='primary'
                    loading={delLoading}
                    disabled={!rowSelectIds || rowSelectIds.length == 0}
                    onClick={() => this.onRightMenuClick('BTN_DEL')}>{getLabel(32136,'批量删除')}
                  </Button>,
                  <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@caieah@exportAll`}
                  type='primary'
                  onClick={() => this.onRightMenuClick('BTN_EXPORT')}>{getLabel(81272,"导出全部")}
                </Button>
                ]}
              >
                <WeaTab ecId={`${this && this.props && this.props.ecId || ''}_WeaTab@42wgq9`}
                  datas = {topTab}
                  keyParam="viewcondition"
                  countParam="groupid"
                  selectedKey={timeSag}
                  onChange={v => {
                    meetingMonitor.setState({timeSag: v});
                    monitorForm.reset();
                    monitorForm.updateFields({timeSag__begindate__enddate: {value : v}});
                    meetingMonitor.getMonitor(true,{...monitorForm.getFormParams(), timeSag: v}); //timeSag需要强制加进去
                  }}
                  searchType={['base', 'advanced']}
                  searchsAd={this.getSearchs()}
                  showSearchAd={showSearchAd}
                  buttonsAd={this.getTabButtonsAd()}
                  setShowSearchAd={() => meetingMonitor.setState({showSearchAd: !showSearchAd})}
                  hideSearchAd={() => meetingMonitor.setState({showSearchAd: false})}
                  searchsBaseValue= {monitorForm.isFormInit && monitorForm.getFormParams() && monitorForm.getFormParams().name || ''}
                  onSearch={() => {meetingMonitor.getMonitor(true)}}
                  onSearchChange={value => {monitorForm.updateFields({name : value})}}
                />
                <WeaTable ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@7yqp87`}
                  comsWeaTableStore={monitorTableStore}
                  hasOrder={true}
                  needScroll={true}
                  onOperatesClick={this.onOperatesClick}
                  getColumns={this.getColumns}
                />
              </WeaTop>
            </WeaRightMenu>

            <MeetingDialog ecId={`${this && this.props && this.props.ecId || ''}_MeetingDialog@bvdb6q`}
              visible={this.state.visible}
              setRoomPlan={this.setRoomPlan}
              setDialog={this.setDialog}
              setType={this.setType}
              setMeetingId={this.setMeetingId}
              setAll={this.setAll}
              type={this.state.dialogType}
              meetingId={this.state.meetingId}
              doRefesh={this.doRefesh}//自定义刷新页面，不会关掉弹出框
              isInterval={false}
              meetingDate={''}
            />
            <RoomPlanDialog ecId={`${this && this.props && this.props.ecId || ''}_RoomPlanDialog@hsl8s6`}
              visible={this.state.RoomPlanContainer}
              setRoomPlan={this.setRoomPlan}
              setDialog={this.setDialog}
              setType={this.setType}
              setMeetingId={this.setMeetingId}
              canCreate={false}
              meetingId={this.state.meetingId}
              height={600}
            />
          </div>:
          <WeaAlertPage ecId={`${this && this.props && this.props.ecId || ''}_WeaAlertPage@pq4wa4`}>
            <div>{getLabel(382663,'暂无权限')}</div>
          </WeaAlertPage>
        }
      </div>
    )
  }
}